export function useContentMenu(widgets, widgetIndex) {
  const visibleContentMenu = ref(false)
  const rightClickIndex = ref(-1)
  const rightClickWidget = ref(null)
  const styleObj = ref<any>({
    left: 0,
    top: 0
  })

  // 右键
  const rightClick = (event, index) => {
    rightClickIndex.value = index
    rightClickWidget.value = widgets.value[index]
    const left = event.clientX
    const top = event.clientY
    if (left || top) {
      styleObj.value = {
        left: left + 'px',
        top: top + 'px',
        display: 'block'
      }
    }

    visibleContentMenu.value = true
    return false
  }

  // 删除
  const deletelayer = () => {
    widgets.value.splice(rightClickIndex.value, 1)
  }

  // 锁定
  const lockLayer = () => {
    const obj = widgets.value[rightClickIndex.value]
    obj.options.position.disabled = true
  }

  // 解除锁定
  const noLockLayer = () => {
    const obj = widgets.value[rightClickIndex.value]
    obj.options.position.disabled = false
  }

  // 置顶
  const istopLayer = () => {
    if (rightClickIndex.value + 1 < widgets.value.length) {
      const temp = widgets.splice(rightClickIndex, 1)[0]
      widgets.value.push(temp)
    }
    widgetIndex.value = widgets.value.indexOf(rightClickWidget)
  }

  // 置底
  const setlowLayer = () => {
    if (rightClickIndex.value !== 0) {
      widgets.value.unshift(widgets.value.splice(rightClickIndex.value, 1)[0])
    }
    widgetIndex.value = widgets.value.indexOf(rightClickWidget.value)
  }

  // 上移一层
  const moveupLayer = () => {
    if (rightClickIndex.value !== 0) {
      widgets.value[rightClickIndex.value] = widgets.value.splice(
        rightClickIndex.value - 1,
        1,
        widgets.value[rightClickIndex.value]
      )[0]
    } else {
      widgets.value.push(widgets.value.shift())
    }
    widgetIndex.value = widgets.value.indexOf(rightClickWidget.value)
  }

  // 下移一层
  const movedownLayer = () => {
    if (rightClickIndex.value !== widgets.value.length - 1) {
      widgets.value[rightClickIndex.value] = widgets.value.splice(
        rightClickIndex.value + 1,
        1,
        widgets.value[rightClickIndex.value]
      )[0]
    } else {
      widgets.value.unshift(widgets.value.splice(rightClickIndex.value, 1)[0])
    }
    widgetIndex.value = widgets.value.indexOf(rightClickWidget.value)
  }

  return {
    visibleContentMenu,
    rightClickIndex,
    rightClickWidget,
    styleObj,
    rightClick,
    deletelayer,
    lockLayer,
    noLockLayer,
    istopLayer,
    setlowLayer,
    moveupLayer,
    movedownLayer
  }
}
